﻿using System.CodeDom.Compiler;
using System.Reflection;
using AutoCADDotNetLibrary;
using Autodesk.AutoCAD.Customization;
using Autodesk.AutoCAD.Runtime;
using Microsoft.CSharp;

namespace NunitTest
{
    public class Init : IExtensionApplication
    {
        /// <summary>
        /// 是否加载完成
        /// </summary>
        public static bool IsLoaded = false;
        public void Initialize()
        {
            ExtensionApplication.Initialize(Assembly.GetExecutingAssembly());

            _codedom = Codedom();
            ExtensionApplication.Initialize(_codedom);

            IsLoaded = true;
        }

        public void Terminate()
        {
            ExtensionApplication.Terminate(Assembly.GetExecutingAssembly());
        }

        [Terminate]
        public void TerminateFunc()
        {
            //卸载插件的使用
            Register.DeleteRegisteredCAD(Assembly.GetExecutingAssembly());

            CustomizationSection cs = new CustomizationSection(CADPath.AcadCUIX);
            cs.CustomizationSection.RemovePartialMenu(CUITest.CUIXFilePath, "NunitTest");
            cs.Save();
        }


        #region 为了测试用，测试其他程序集的[Initialize]

        private static Assembly _codedom;

        public static object GetTestValue()
        {
            return _codedom.GetType("Codedom.Ass").GetField("i").GetValue(null);
        }
        //https://docs.microsoft.com/zh-cn/dotnet/framework/reflection-and-codedom/dynamic-source-code-generation-and-compilation
        public static Assembly Codedom()
        {
            CompilerParameters parameter = new CompilerParameters();
            parameter.ReferencedAssemblies.Add("System.dll");
            //加入CAD的编译的dll
            string[] dlls = new string[]
            {
                typeof(InitializeAttribute).Assembly.Location,
            };
            foreach (string item in dlls)
            {
                parameter.ReferencedAssemblies.Add(item);
            }

            parameter.GenerateExecutable = false;
            parameter.GenerateInMemory = true;

            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerResults result = provider.CompileAssemblyFromSource(parameter, @"

using AutoCADDotNetLibrary;

namespace Codedom
{
    public class Ass
    {

        public static int i = 0;

        [Initialize]
        public void Initialize()
        {
            i = 1;
        }
    }
}
");

            if (result.Errors.Count > 0)
            {
                System.Diagnostics.Debugger.Break();
            }

            return result.CompiledAssembly;
        }

        #endregion
    }
}

